%include "condef.inc"

[bits 16]
[section .text]

@@con_seg   dw 0xb800                           ; initial values for standard 80x25 text mode (3)
@@con_cx    dw 80
@@con_cy    dw 25

@@con_px    db 0
@@con_py    db 0
@@con_color db 0x07

proc        _con_init
            push        cs
            pop         es
            mov         di, @@con_4096
            mov         ax, 0x4f00              ; checking VBE stuff
            int         0x10
            or          ah, ah
            jnz         @@VBEfails              ; AH == 0 - VBE present

            mov         bx, _VID_TEXT_80X60
            mov         ax, 0x4f02              ; setup high resolution text mode
            int         0x10
            or          ah, ah
            jnz         @@VBEfails
            mov         word [cs:@@con_seg], 0xb800
            mov         word [cs:@@con_cx], 80
            mov         word [cs:@@con_cy], 60
            jmp         _con_reset
            ret

@@VBEfails: mov         al, _VID_TEXT_80X25
            xor         ah, ah
            int         0x10
            mov         word [cs:@@con_seg], 0xb800
            mov         word [cs:@@con_cx], 80
            mov         word [cs:@@con_cy], 25

_con_reset: xor         dh, dh
            mov         [cs:@@con_px], dh
            mov         [cs:@@con_py], dh            
            mov         byte [cs:@@con_color], 0x07
            ret
endproc            

_set_xy:    mov         [cs:@@con_px], _REG_X
            mov         [cs:@@con_py], _REG_Y
            ret
            
_set_color: mov         [cs:@@con_color], _REG_COLOR
            ret
            
_output:    mov         es, [cs:@@con_seg]
            xor         dh, dh
            mov         dl, [cs:@@con_py]
            mov         ax, [cs:@@con_cx]
            imul        ax, dx
            xor         bh, bh
            mov         bl, [cs:@@con_px]
            shl         bx, 1
            mov         di, bx
            add         di, ax
            mov         ah, [cs:@@con_color]
@@print:    lodsb
            or          al, al
            jz          @@done
            stosw
            jmp         @@print
@@done:     ret

_con_cls:   call        _set_color
            mov         es, [cs:@@con_seg]
            mov         cx, [cs:@@con_cx]
            imul        cx, [cs:@@con_cy]
            xor         di, di
            mov         al, 0x20
            rep stosw
            ret


[section .bss]
;
; Console memory reserve
;
@@con_8192  resb 4096
@@con_4096  resb 4096
